﻿using OnHook.Business.IServices;
using OnHook.Business.IServices.Common;
using OnHook.Business.Model;
using OnHook.Business.Vo.UserInfo;
using OnHook.Common;
using OnHook.Common.Extension;
using OnHook.Domain.Entities;
using OnHook.Framework.Ioc;
using OnHook.Common.UtilsHelper;
using EasyTool;
using Mapster;
using SqlSugar;

namespace OnHook.Business.Services
{
    /// <summary>
    /// 用户服务
    /// </summary>
    public class UserInfoService(ISqlSugarClient db,IJwtService jwtService) : IUserService,IScoped
    {

        /// <summary>
        /// 数据库
        /// </summary>
        protected readonly ISqlSugarClient _db = db;
        /// <summary>
        /// Jwt服务
        /// </summary>
        private readonly IJwtService _jwtService = jwtService;


        /// <summary>
        /// 检查是否有此用户
        /// </summary>
        /// <param name="model"></param>
        /// <param name="updateUser"></param>
        /// <returns></returns>
        public async Task<UserInfo> CheckUserInfoAsync(OpenUserInfoModel model, bool updateUser)
        {
            OpenInfo openInfo = null!;
            long userid = IdHelper.NextId();

            #region 处理OpenInfo
            if (model.UnionId.IsNotEmpty())
            {
                openInfo = await _db.Queryable<OpenInfo>().FirstAsync(c => c.UnionId == model.UnionId);
            }
            if (openInfo.IsNull())
            {
                openInfo = await _db.Queryable<OpenInfo>().FirstAsync(c => c.OpenId == model.OpenId);
            }
            if (openInfo.IsNull())
            {
                return null!;
            }

            #endregion

            userid = openInfo.UserId;
            var user = await _db.Queryable<UserInfo>().FirstAsync(c => c.Id == userid);
            if (user != null && updateUser)
            {
                user.IconUrl = model.HeadImgUrl.IsEmpty() ? user.IconUrl : model.HeadImgUrl;
                user.NickName = model.NickName.IsEmpty() ? user.NickName : model.NickName;
                user.Province = model.Province.IsEmpty() ? user.Province : model.Province;
                user.City = model.City.IsEmpty() ? user.City : model.City;
                user.Country = model.Country.IsEmpty() ? user.Country : model.Country;
                await _db.Updateable(user).ExecuteCommandAsync();

            }
            return user!;
        }


        /// <summary>
        /// 登录，其实就是生成tkn并记录
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public async Task<LoginUserVo> LoginUser(UserInfo userInfo)
        {
            var vo = userInfo.Adapt<LoginUserVo>();

            vo.OpenInfos = (await _db.Queryable<OpenInfo>().Where(c => c.UserId == userInfo.Id).ToListAsync()).Adapt<List<OpenInfoVo>>();
            vo.Token = _jwtService.Generate(vo);
            return vo;
        }
    }
}
